package com.example.lzbase;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;


import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OSUtils;
import com.kaopiz.kprogresshud.KProgressHUD;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.annotation.ColorRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.MainThread;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.lifecycle.AndroidViewModel;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Optional;
import event.MessageEvent;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;


public abstract class BaseActivity  extends BasePermissionsActivity {
    private KProgressHUD HUD;
    public void showLoading(boolean show){

        if(HUD==null){
            HUD = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setCancellable(false)
                    .setDimAmount(0.1f);
        }
        if(show){
            HUD.show();
        }
        else {
            HUD.dismiss();
        }




    }


    @Nullable

    protected  ImageButton buttonBack;
    @Nullable

    protected  TextView textTitle;
    @Nullable

    protected  ImageButton buttonRight;

    @Nullable

    protected  TextView textTitleRight;

    //返回事件,可能无此id

    public void onBackClick() {
        back();
    }
    protected void back() {

        onBackPressed();
    }
    //设置标题
    protected void setTitleText(@StringRes int resId) {
        if (null != textTitle) setTitleText(getResources().getString(resId));
    }

    protected void setTitleText(String text) {
        if (null != textTitle) textTitle.setText(text);
    }
    protected abstract @StringRes int  titleText();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        initStatusBar();
        initBase();
        created(savedInstanceState);

    }
    //设置标题
    protected void setTitleRight(String text) {
        if (null != textTitleRight) {
            textTitleRight.setText(text);
            textTitleRight.setVisibility(View.VISIBLE);
        }
    }
    //
    protected void setImageRight(int image) {
        if (null != buttonRight) {
            buttonRight.setImageResource(image);
            buttonRight.setVisibility(View.VISIBLE);
        }
    }
    /**
     * 初始化 EventBus ButterKnife
     */
    private void initBase() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        EventBus.getDefault().register(this);
        ButterKnife.bind(this);
        textTitle = findViewById(R.id.nav_title);
        buttonBack = findViewById(R.id.nav_back);
        buttonRight= findViewById(R.id.nav_right);
        textTitleRight = findViewById(R.id.nav_title_right);
        if(null!=buttonBack)
            buttonBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    back();
                }
            });
        setTitleText(titleText());
        if(null!=textTitleRight)
            textTitleRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    titleRightClick();
                }
            });
        if(buttonRight!=null){
            buttonRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    titleRightClick();
                }
            });
        }
    }

    protected void titleRightClick() {
    }

    protected abstract void created(@Nullable Bundle savedInstanceState);
    /**
     *
     * @param event 广播事件监听
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */};

    /**
     *
     * @return 布局id
     */
    @LayoutRes
    protected abstract int getLayoutId();

    /**
     * 初始化状态栏
     */

    public void initStatusBar(){
        ImmersionBar.with(this)
                .fitsSystemWindows(false)  //使用该属性,必须指定状态栏颜色
                .statusBarDarkFont(statusBarDarkFont())
                .statusBarColor( statusColor())
                .statusBarView(findViewById(R.id.status_view))
                .init();
    }
    @ColorRes
    public  int statusColor(){
        return  R.color.color_transparent;
    }

    public  boolean statusBarDarkFont(){
        return  false;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 必须调用该方法，防止内存泄漏
        ImmersionBar.with(this).destroy();
        EventBus.getDefault().unregister(this);

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 非必加
        // 如果你的app可以横竖屏切换，适配了4.4或者华为emui3.1系统手机，并且navigationBarWithKitkatEnable为true，
        // 请务必在onConfigurationChanged方法里添加如下代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、android4.4或者华为emui3.1系统手机；3、navigationBarWithKitkatEnable为true）
        // 否则请忽略
        ImmersionBar.with(this).init();
    }
    @Override
    protected void onResume() {
        super.onResume();
        // 非必加
        // 如果你的app可以横竖屏切换，适配了华为emui3系列系统手机，并且navigationBarWithEMUI3Enable为true，
        // 请在onResume方法里添加这句代码（同时满足这三个条件才需要加上代码哦：1、横竖屏可以切换；2、华为emui3系列系统手机；3、navigationBarWithEMUI3Enable为true）
        // 否则请忽略
        if (OSUtils.isEMUI3_x()) {
            ImmersionBar.with(this).init();
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }



        return super.dispatchTouchEvent(ev);

    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        overridePendingTransition(R.anim.on_activity_open,R.anim.on_activity_puse);


    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.on_activity_open,R.anim.on_activity_puse);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.on_activity_reopen,R.anim.on_activity_close);

    }

    @Override
    protected void onStop() {
        super.onStop();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }
}
